/**
 * 
 */
package download;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import scan.FileScanServlet;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;

/**
 * @author mareshkau
 *
 */
public class FileDownloadServlet extends HttpServlet {


	private static final long serialVersionUID = 3860875560686805595L;

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			String downloadFileName = req.getParameter("downloadPath");
			String userName = this.getServletContext().getInitParameter(FileScanServlet.USER_NAME);
			String userPassword = this.getServletContext().getInitParameter(FileScanServlet.USER_PASS);
			String workgroup = this.getServletContext().getInitParameter(FileScanServlet.WORKGROUP);
			SmbFile smbFile = new SmbFile(downloadFileName,new NtlmPasswordAuthentication(workgroup,userName,userPassword));
			try{
				smbFile.exists();
				smbFile.canRead();
			} catch (Exception ex) {
	        	PrintWriter out = resp.getWriter();
			    out.println("Cann't get File: "+downloadFileName);
			    out.close();
			    return;
			}
			if(smbFile.exists() && smbFile.canRead()){
	            resp.setStatus(HttpServletResponse.SC_OK);
		        resp.setBufferSize(1024*1024);
		        resp.setContentType("text/html; charset=UTF-8");
		        resp.getContentType();
		        resp.setHeader("content-disposition", "attachment; filename=" + smbFile.getName().replaceAll("\\s", "_"));
		        OutputStream outputStream = resp.getOutputStream();
		        InputStream  inputStream = smbFile.getInputStream();
		        byte[] buffer = new byte[1024*1024];
		        int bytesCount = 0;
		        while ((bytesCount = inputStream.read(buffer)) > -1) {
		            outputStream.write(buffer, 0, bytesCount);
		            outputStream.flush();		           
		        }
		        inputStream.close();
		        resp.flushBuffer();
		        outputStream.close();
			} else {
	        	PrintWriter out = resp.getWriter();
			    out.println("Cann't get File: "+downloadFileName);
			    out.close();
	        }
	}



}
